<template>
  <div>
    <el-form :model="channelDetail" :rules="rules" ref="editChannelForm" label-width="100px" >
      <el-form-item label="渠道名称" prop="channel_name">
        <el-input class="short" v-model="channelDetail.channel_name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('editChannelForm')">立即保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import { Form, FormItem, Input, Button } from 'element-ui'
  import { mapActions } from 'vuex'
  import Q from 'q'
  import N from '../lib/notification'
  export default {
    props: {
      isEdit: {
        type: Boolean
      }
    },
    components: {
      [Form.name]: Form,
      [FormItem.name]: FormItem,
      [Input.name]: Input,
      [Button.name]: Button
    },
    data () {
      return {
        rules: {
          channel_name: [
            { required: true, message: '请输入渠道名称', trigger: 'blur' }
          ]
        },
        channelId: null,
        channelDetail: {
          channel_name: null
        }
      }
    },
    methods: {
      submitForm (formName) {
        Q.Promise((resolve, reject) => {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              resolve()
            } else {
              console.log('error submit!!')
              return false
            }
          })
        }).then(() => {
          this.saveChannel(this.channelDetail).then((response) => {
            if (response.data.errcode === 0) {
              N.notify('success', response.data.errmsg)
              this.$router.replace({ path: '/channels' })
            } else {
              N.notify('error', response.data.errmsg)
            }
          }).catch((err) => {
            console.log(err)
            N.notify('error', '系统出错...编辑保存失败...请联系管理员！')
          })
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      trim (str) { // 删除左右两端的空格
        return str.replace(/(^\s*)|(\s*$)/g, '')
      },
      ...mapActions({
        saveChannel: 'saveChannel'
      })
    },
    mounted () {
      const channelName = this.$route.query.channel_name
      this.channelId = this.$route.params.id
      this.channelDetail = {
        channel_name: this.trim(channelName),
        channel_id: this.channelId
      }
      console.log('this.channelId', this.channelId)
    }
  }
</script>
